import { prisma } from "@/lib/prisma"
import { getServerSession } from "next-auth"
import { NextResponse } from "next/server"
import { authOptions } from "@/lib/auth"

export async function DELETE(
  req: Request,
  context: { params: { id: string } }
) {
  const { id } = await Promise.resolve(context.params)
  
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.isAdmin) {
      return NextResponse.json({ error: "未授权访问" }, { status: 401 })
    }

    await prisma.eventLibrary.delete({
      where: { id }
    })

    return NextResponse.json({ success: true })

  } catch (error) {
    return NextResponse.json(
      { error: "删除事件库失败" },
      { status: 500 }
    )
  }
}

export async function GET(
  req: Request,
  context: { params: { id: string } }
) {
  const { id } = await Promise.resolve(context.params)
  
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.isAdmin) {
      return NextResponse.json({ error: "未授权访问" }, { status: 401 })
    }

    const library = await prisma.eventLibrary.findUnique({
      where: { id }
    })

    if (!library) {
      return NextResponse.json({ error: "事件库不存在" }, { status: 404 })
    }

    return NextResponse.json(library)

  } catch (error) {
    return NextResponse.json(
      { error: "加载事件库失败" },
      { status: 500 }
    )
  }
}

export async function PATCH(
  req: Request,
  context: { params: { id: string } }
) {
  const { id } = await Promise.resolve(context.params)
  
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.isAdmin) {
      return NextResponse.json({ error: "未授权访问" }, { status: 401 })
    }

    const { name, description } = await req.json()

    const library = await prisma.eventLibrary.update({
      where: { id },
      data: { name, description }
    })

    return NextResponse.json(library)

  } catch (error) {
    return NextResponse.json(
      { error: "更新事件库失败" },
      { status: 500 }
    )
  }
} 